import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {Image, Navigator, View} from '@tarojs/components'
import {connect} from 'react-redux'
import {
  CityLocation as CityLocationType,
  Good,
} from '../../utils/server.interface'
import {user} from '../../utils/user.service'
import {http} from "../../utils/http";
import {PAY_SUCCESS_QR, RESOURCE_URL, TARO_ENV} from "../../constants/api";
import fetchNewGoodsList from "../../utils/fetchNewGoodsList";
import Headercar from "../components/header-car/header-car";
import {getHeadTop, vcmonitor} from "../../utils/tools";
import GoodsBox from '../../components/small-goods-box/small-goods-box'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './success.scss'

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  searchBarTop: number
  pay: number
  typeName: string
  limit: number
  list: Good[]
  qrCodeImg: string
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class Index extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    searchBarTop: 0,
    pay: 0,
    typeName: '',
    limit: 10,
    list: [],
    qrCodeImg: ''
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    this.shareParams = await user.getSellerParams()
    const headTop: any = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 40)
    const {pay = 0} = Taro.getCurrentInstance().router.params
    const {typeName} = Taro.getCurrentInstance().router.params
    this.setState({pay, typeName, searchBarTop}, async () => {
      const list = await this.getAdds(this.page)
      this.setState({list})
    })
    if (process.env.IS_SHOW_LIVING_CODE) {
      await this.paySuccessQr();
    }
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  showImg(img) {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img]// 需要预览的图片http链接列表
    })
  }

  async getAdds(page = 1) {
    const {limit} = this.state
    // 商品列表
    const indexGoods = await fetchNewGoodsList.getGoodsList({
      module_type: "4",
      data_type: "0",
      page: page,
      length: 10,
      // region_region: this.props.location.region_id
      region_region: ""
    });
    if (indexGoods && Array.isArray(indexGoods)) {
      if (indexGoods.length < limit) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return indexGoods
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getAdds(this.page)
      this.setState({list: [...old, ...newData]})
    }
  }

  async paySuccessQr() {
    const res = await http.HGet(PAY_SUCCESS_QR, {order_num: ''})
    if (res) {
      this.setState({qrCodeImg: res.data.code});
    }
  }

  render() {
    const {typeName, pay, searchBarTop, list, qrCodeImg} = this.state
    const _env = Taro.getCurrentInstance().router.params.env;
    return (
      <View className='success-order-root'>
        <GzhAuth />
        {process.env.TARO_ENV !== 'h5' && process.env.TARO_ENV !== 'tt' && <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <Headercar shu='#000' color='black' title=' ' tabColor='#000' backgroundColor='none' bcolor='#000' />
        </View>}
        <View className={`pay-success ${TARO_ENV + 'pay-success'}`}>
          <View className='pay-status'>
            <Image className='img' src={RESOURCE_URL + '/upload/file/dbd7e871d3504791b8ff31fc91e0bf02.png'} />
            {pay > -1 ? '支付成功' : '兑换成功'}
          </View>
          {pay > -1 ? <View className='pay'>实付金额：￥{pay}</View> : <View className='pay_zhan' />}
        </View>
        <View className='pay-info'>
          {qrCodeImg && qrCodeImg !== 'variable_code_close' &&<View className='qr-code'>
            <Image onClick={this.showImg.bind(this, qrCodeImg)} src={qrCodeImg} className='qr-code-lead-in' />
          </View> }
          <View className='link'>
            {_env != 'pc' && <Navigator url='/pages/index/index' openType='switchTab' className='go-info'>
              返回首页
            </Navigator>}
            {typeName == 'md' && _env != 'pc' && <Navigator url='/other/buy-order/billingdetail' className='go-info'>
              订单详情
            </Navigator>}
            {typeName !== 'md' && _env != 'pc' && <Navigator url='/main/order/order?status=-1' className='go-info'>
              订单详情
            </Navigator>}
          </View>
        </View>
        {list.length > 0 && <View className='recommend-goods-box'>
          <View className='good'>
            <GoodsBox data={list} />
          </View>
        </View>}
      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
